package practica1.actions;

import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import practica1.Practica1;
import practica1.controller.Controller;
import practica1.language.Language;
import practica1.language.LanguageEvent;
import practica1.language.LanguageListener;
import practica1.logic.LogicExperimento;
import practica1.manejoExperimento.ExperimentoInvalidoException;
import practica1.manejoExperimento.ManejoExperimento;

/**
 * Clase que implementa la acción para guardar un experimento
 * @author Miguel González - Ceura
 */
public class ActionGuardar extends AbstractAction implements LanguageListener {

    /**
     * Constructor de la clase
     */
    public ActionGuardar() {
        super(Language.getI().getP("GUARDAR"), null);

        Language.getI().addLanguageListener(this);
        
        putValue(SHORT_DESCRIPTION, Language.getI().getP("GUARDAR_EXPERIMENTO"));
        putValue(NAME, Language.getI().getP("GUARDAR"));
        putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_G, 
                InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK));
        putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_G));
        putValue(SELECTED_KEY, Boolean.TRUE);
    }
    
    /**
     * Cuando sucede la acción nos encargamos de guardar el experimento seleccionado
     * @param e ActionEvent
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        LogicExperimento exp = Controller.getInstance().
                getExperimentoSeleccionado();
        
        try {
            ManejoExperimento.guardarExperimento(exp);
        } catch (ExperimentoInvalidoException ex) {
            Practica1.log.error(Language.getI().getP("ERROR"), ex);
            JOptionPane.showMessageDialog(Practica1.getInstance(),
                Language.getI().getP("PROBLEMA_GUARDAR"), 
                Language.getI().getP("ERROR"), JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * Al cambiar el idioma actualizamos el nombre y la descripción
     * @param evt LanguageEvent
     */
    @Override
    public void idiomaChange(LanguageEvent evt) {
        putValue(SHORT_DESCRIPTION, Language.getI().getP("GUARDAR_EXPERIMENTO"));
        putValue(NAME, Language.getI().getP("GUARDAR"));
    }
}
